package org.example.elm_xiangmu.captcha;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.example.elm_xiangmu.result.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.example.elm_xiangmu.captcha.dto.CaptchaRO;
import org.example.elm_xiangmu.captcha.dto.CaptchaVO;
import org.example.elm_xiangmu.captcha.service.CaptchaImageGenerator;
import org.example.elm_xiangmu.captcha.service.CaptchaService;

import java.io.IOException;
import java.util.Base64;

@CrossOrigin
@RestController
@RequestMapping("/Captcha")
@Tag(name = "captcha", description = "验证码相关接口")
public class CaptchaController {
    @Autowired
    private  CaptchaService captchaService;

    // 返回 CaptchaVO 的 API
    @Operation(summary = "获取验证码")
    @GetMapping("/getCaptcha")
    public Result getCaptcha() throws IOException {
        var captchaData = captchaService.createCaptchaData(4, false);
        var captchaImgBytes = CaptchaImageGenerator.generateJpegImg(captchaData.getCode(), 100, 30);

         CaptchaVO  captchaVO = new CaptchaVO(captchaData.getId(),Base64.getEncoder().encodeToString(captchaImgBytes));
         return Result.success(captchaVO);
    }

    @Operation(summary = "验证验证码", description = "验证用户输入的验证码是否正确")
    @PostMapping("/verifyCaptcha")
    public Result validateCaptcha(@RequestBody CaptchaRO Ro) {
        Boolean bool = captchaService.validateCaptcha(Ro);
        if (bool == false){
            return Result.error("验证码验证失败");
        }
        else {
            return Result.success(true,"验证成功");
        }
    }
}